package com.smartum.mpr.utils;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {

	private static final int BUFFER = 2048;

	public static void handleUploadedFile(MultipartFile multiPartFile, String path) throws IOException {

		InputStream is = null;
		OutputStream os = null;

		if (multiPartFile.getSize() > 0) {
			try {
				File targetFile = new File(path);
				if (!targetFile.exists()) {
					Logger.getLogger(FileUtil.class).info("file is not exists: " + path);
					targetFile.getParentFile().mkdirs();
					Logger.getLogger(FileUtil.class).info("create new file");
					targetFile.createNewFile();
				}
				is = multiPartFile.getInputStream();
				os = new FileOutputStream(path);
				int readBytes = 0;
				byte[] buffer = new byte[BUFFER];
				while ((readBytes = is.read(buffer, 0, BUFFER)) != -1) {
					os.write(buffer, 0, BUFFER);
				}
				Logger.getLogger(FileUtil.class).info("end writing the file");
			} finally {
				Logger.getLogger(FileUtil.class).info("close streams");
				closeStream(os);
				closeStream(is);
			}
		}
	}

	private static void closeStream(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				Logger.getLogger(FileUtil.class).info("error while close stream");
				Logger.getLogger(FileUtil.class).info("error message: " + e.getMessage());
			}
		}
	}

}
